package com.ruoyi.oar.controller.pc;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Response;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ToolUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.oar.controller.vo.OarImpNetHousePartField;
import com.ruoyi.oar.domain.dto.OarImpNetHouseDTO;
import com.ruoyi.oar.domain.query.OarImpNetHouseQuery;
import com.ruoyi.oar.service.OarImpNetHouseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * 导入的网约房Controller
 *
 * @author ruoyi
 * @date 2022-02-24
 */
@Api(tags = "PC端导入的网约房")
@RestController
@RequestMapping("/pc/oar-imp-net-houses")
public class PcImpNetHouseController extends BaseController
{
    @Autowired
    private OarImpNetHouseService oarImpNetHouseService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 查询临时网约房列表
     */
    @ApiOperation("查询临时网约房列表")
    @GetMapping
    public TableDataInfo<OarImpNetHouseDTO> list(OarImpNetHouseQuery oarImpNetHouseQuery){
        logger.debug("查询临时网约房列表,查询条件oarImpNetHouseQuery={}",JSONObject.toJSONString(oarImpNetHouseQuery));
        startPage();
        //oarImpNetHouseQuery.setCreateBy(getUserId());
        return oarImpNetHouseService.findAll(oarImpNetHouseQuery);
    }

    /**
     * 导出临时网约房列表
     */
    @ApiOperation("导出临时网约房列表")
    @Log(title = "临时网约房", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response,@RequestParam(required = false) @ApiParam("任务id") String taskId){
        if(ToolUtil.isEmpty(taskId)){
            throw new ServiceException("taskId不能为空");
        }
        List<OarImpNetHouseDTO> list = oarImpNetHouseService.selListByTaskId(taskId);
        ExcelUtil<OarImpNetHouseDTO> util = new ExcelUtil<OarImpNetHouseDTO>(OarImpNetHouseDTO.class);
        util.exportExcel(response,list, "临时网约房数据");
    }

    /**
     * 导出临时网约房列表
     */
    @ApiOperation("导出临时网约房部分字段列表")
    @Log(title = "临时网约房部分字段", businessType = BusinessType.EXPORT)
    @PostMapping("/exportPartFile")
    public void exportPartFile(HttpServletResponse response,OarImpNetHouseQuery oarImpNetHouseQuery){
        logger.debug("查询临时网约房列表,导出条件oarImpNetHouseQuery={}",JSONObject.toJSONString(oarImpNetHouseQuery));
        //oarImpNetHouseQuery.setCreateBy(getUserId());
        List<OarImpNetHousePartField> list = oarImpNetHouseService.selectOarImpNetHousePartList(oarImpNetHouseQuery);
        ExcelUtil<OarImpNetHousePartField> util = new ExcelUtil<OarImpNetHousePartField>(OarImpNetHousePartField.class);
        util.exportExcel(response,list, "临时网约房数据");
    }

    /**
     * 获取临时网约房房详细信息
     */
    @ApiOperation("获取临时网约房详细信息")
    @GetMapping(value = "/{id}")
    public Response<OarImpNetHouseDTO> getInfo(@PathVariable("id") @ApiParam("临时网约房ID") String id) {
        logger.debug("获取临时网约房详细信息,id={}",id);
        checkId(id);
        return Response.success(oarImpNetHouseService.selectOarImpNetHouseById(id).orElseThrow(()->new ServiceException("无效的ID")));
    }

    /**
     * 新增临时网约房
     */
    @ApiOperation("新增临时网约房")
    @Log(title = "临时网约房", businessType = BusinessType.INSERT)
    @PostMapping
    @RepeatSubmit
    public AjaxResult add(@RequestBody OarImpNetHouseDTO oarImpNetHouseDTO) {
        logger.debug("新增临时网约房,oarImpNetHouseDTO={}",JSONObject.toJSONString(oarImpNetHouseDTO));
        return toAjax(oarImpNetHouseService.insertOarImpNetHouse(oarImpNetHouseDTO));
    }

    /**
     * 修改临时网约房
     */
    @ApiOperation("修改临时网约房")
    @Log(title = "临时网约房", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OarImpNetHouseDTO oarImpNetHouseDTO) {
        logger.debug("修改导入的网约房,oarImpNetHouseDTO={}",JSONObject.toJSONString(oarImpNetHouseDTO));
        checkId(oarImpNetHouseDTO.getId());
        return toAjax(oarImpNetHouseService.updateOarImpNetHouse(oarImpNetHouseDTO));
    }

    /**
     * 删除临时网约房
     */
    @ApiOperation("删除临时网约房")
    @Log(title = "临时网约房", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        logger.debug("删除临时网约房,ids={}",JSONObject.toJSONString(ids));
        Arrays.asList(ids).forEach(this::checkId);
        return toAjax(oarImpNetHouseService.deleteOarImpNetHouseByIds(ids));
    }

    @ApiOperation("临时网约房模板下载")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<OarImpNetHousePartField> util = new ExcelUtil<OarImpNetHousePartField>(OarImpNetHousePartField.class);
        util.importTemplateExcel(response, "用户数据");
    }

    @ApiOperation("导入临时网约房部分字段列表")
    @Log(title = "导入临时网约房部分字段列表", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        //String userId = getUserId();
        //String key = RedisConstants.REDIS_NET_HOUSE_IMP_KEY + userId;
        //String dataKey = RedisConstants.REDIS_NET_HOUSE_IMP_DATA + userId;
        //if (redisCache.exists(key)) {
        //    throw new ServiceException("导入中，请勿稍后操作");
        //}
        //redisCache.setCacheObject(key, "导入中", 20, TimeUnit.SECONDS);
        try {
            ExcelUtil<OarImpNetHousePartField> util = new ExcelUtil<OarImpNetHousePartField>(OarImpNetHousePartField.class);
            List<OarImpNetHousePartField> userList = util.importExcel(file.getInputStream());
            //redisCache.setCacheObject(dataKey, userList);
        } finally {
            //redisCache.deleteObject(key);
        }
        return AjaxResult.success();
    }

    @ApiOperation("导入临时网约房")
    @Log(title = "导入临时网约房", businessType = BusinessType.IMPORT)
    @PostMapping("/importDataFull")
    public AjaxResult importDataFull(MultipartFile file) throws Exception {
        //String userId = getUserId();
        //String key = RedisConstants.REDIS_NET_HOUSE_IMP_FULL_KEY + userId;
        //if (redisCache.exists(key)) {
        //    throw new ServiceException("导入中，请勿稍后操作");
        //}
        //redisCache.setCacheObject(key, "导入中", 20, TimeUnit.SECONDS);
        try {
            ExcelUtil<OarImpNetHouseDTO> util = new ExcelUtil<OarImpNetHouseDTO>(OarImpNetHouseDTO.class);
             List<OarImpNetHouseDTO> houseList = util.importExcel(file.getInputStream());
            oarImpNetHouseService.batchUpdate(houseList);
        } finally {
            //redisCache.deleteObject(key);
        }
        return AjaxResult.success();
    }

    ///**
    // * 查询临时网约房列表
    // */
    //@ApiOperation("查询临时网约房列表")
    //@GetMapping(value = "getRedisList")
    //public AjaxResult getRedisList(){
    //    String userId = getUserId();
    //    String dataKey = RedisConstants.REDIS_NET_HOUSE_IMP_DATA + userId;
    //    List<OarImpNetHousePartField> userList = redisCache.getCacheObject(dataKey);
    //    return AjaxResult.success(userList);
    //}

    @ApiOperation("添加临时网约房列表到数据库")
    @PostMapping(value = "insetNetHouse")
    public AjaxResult insetNetHouse(@RequestParam(required = false) @ApiParam("批次名称") String batchName){
        if(ToolUtil.isEmpty(batchName)){
            throw new ServiceException("batchName不能为空");
        }
        //String userId = getUserId();
        //String dataKey = RedisConstants.REDIS_NET_HOUSE_IMP_DATA + userId;
        //List<OarImpNetHousePartField> oarImpNetHouseList = redisCache.getCacheObject(dataKey);
        //oarImpNetHouseService.batchImpNetHouse(oarImpNetHouseList,batchName);
        //redisCache.deleteObject(dataKey);
        return AjaxResult.success();
    }


    /**
     * 批量更新临时网约房为已选
     */
    @ApiOperation("批量更新临时网约房为已选")
    @Log(title = "批量更新临时网约房为已选", businessType = BusinessType.UPDATE)
    @PutMapping(value = "updateIsCheck")
    public AjaxResult updateIsCheck(@RequestBody OarImpNetHouseDTO oarImpNetHouseDTO) {
        if(ToolUtil.isEmpty(oarImpNetHouseDTO.getIds())){
            throw new ServiceException("Ids不能为空");
        }
        if(ToolUtil.isEmpty(oarImpNetHouseDTO.getIsCheck())){
            throw new ServiceException("isCheck不能为空");
        }
        OarImpNetHouseDTO impNetHouse = new OarImpNetHouseDTO();
        impNetHouse.setIds(oarImpNetHouseDTO.getIds());
        impNetHouse.setIsCheck(oarImpNetHouseDTO.getIsCheck());
        return toAjax(oarImpNetHouseService.updateOarImpNetHouseByIds(impNetHouse));
    }

    //@ApiOperation("待核查网约房数量")
    //@GetMapping(value = "countByIsCheck")
    //public AjaxResult countByIsCheck(){
    //    String userId = getUserId();
    //    return AjaxResult.success(oarImpNetHouseService.countByIsCheck(userId,"1"));
    //}



    /**
     * 根据任务id查询临时网约房列表
     */
    @ApiOperation("根据任务id查询临时网约房列表")
    @GetMapping(value = "selectOarImpNetHouseByTaskId")
    public TableDataInfo<OarImpNetHouseDTO> selectOarImpNetHouseByTaskId(@RequestParam(required = false) @ApiParam("任务id") String taskId){
        startPage();
        return oarImpNetHouseService.selectOarImpNetHouseByTaskId(taskId);
    }

    /**
     * 校验
     * @param id
     */
    private void checkId(String id) {
        Optional.ofNullable(id).orElseThrow(() -> new ServiceException("ID不能为空"));
        oarImpNetHouseService.selectOarImpNetHouseById(id).orElseThrow(() -> new ServiceException("无效的ID"));
    }
}
